package com.cytangaa.searchyoutube;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.Html;
import android.text.Spanned;
import android.util.Log;
public class SearchYoutube {
	public static final String searchTextStart="http://gdata.youtube.com/feeds/api/videos/-/";
	public static final String searchTextMid1="?v=2&format=1&start-index=";
	public static final String searchTextMid2="&max-results=10&orderby=";
	public static final String searchTextEnd="&alt=jsonc";
	public static final String searchOr="|";
	public static final String searchExOr="-";
	public static final String nl = System.getProperty("line.separator");
	public static final String space=" ";
	public static int arrayCounter = 0;
	
	public static String searchOrder="relevance";	
	public static String recommendedSearchStart = "http://youlike.knowithk.com/AddGetVideo.php?page=";
	public static String recommendedSearchEnd = "&category=";
	
	public static String categorySearchStart ="http://gdata.youtube.com/feeds/api/standardfeeds/";//add counrty
	public static String categorySearchMid1 ="/recently_featured_";//add category
	public static String categorySearchMid2 ="/?v=2&format=1&start-index=";
	public static String categorySearchEnd = "&max-results=10&alt=jsonc";
	
	
	

	
	public String SearchLink(String keywords, String order, String index){
		if(order!=null){
			searchOrder=order;
		}
		return searchTextStart+keywords+searchTextMid1+index+searchTextMid2+searchOrder+searchTextEnd ;
	}
	
	public String SearchCategoryLink(String country, String category, String index){
		return categorySearchStart+country+categorySearchMid1+category+categorySearchMid2+index+categorySearchEnd;
	}
	
	public String SearchCustomServer(String category, String index){
		return recommendedSearchStart+index+recommendedSearchEnd+category;
	}
	
	public String YoutubeResult(String link){
		//String response=null;
		String result = null;
		Log.i("YoutubeResult Downloading task","The link:" +link);
		BufferedReader in = null;
        try {
        	link=link.replace(" ","%20");
        	java.net.URLEncoder.encode(link, "utf-8");
    		Log.i("YoutubeResult Downloading task","The link:" +link);
        	DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            result = sb.toString();
            Spanned tempres =Html.fromHtml(result);
            result=tempres.toString();
            return result;
        } catch (URISyntaxException e) {
			// TODO Auto-generated catch block
    		Log.i("YoutubeResult URISyntaxException","The link:" +e);
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			Log.i("YoutubeResult ClientProtocolException","The link:" +e);
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.i("YoutubeResult IOException","The link:" +e);
			e.printStackTrace();
		} finally {
            if (in != null) {
                try {
                	//releaseClient();
                    in.close();            	    
                    //return result;
                } catch (IOException e) {
                    e.printStackTrace();
            	    //return result;
                }
            }
        }
	    //String space=" ";
	    //response= response.replaceAll(space,"");
	    //Log.v("In YoutubeResult", "Response : " +result);
		return result;
	    
	}
	
	public String[] YoutubeJSONToString(String Json){
		arrayCounter = 0;
		if(Json!=null){
			JSONObject jsonRaw;
			String[] videoInfo = new String[100];
			JSONArray jsonArray;
			try {
				jsonRaw = new JSONObject(Json);
				JSONObject dataObject = jsonRaw.getJSONObject("data"); // this is the "data": { } part
				jsonArray = dataObject.getJSONArray("items");
				int counter=0;
				for (int i = 0; i < (jsonArray.length()); i++) {	
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					videoInfo[counter]=jsonObject.getString("id");
					counter++;
					videoInfo[counter]=jsonObject.getString("uploaded");
					counter++;
					if(jsonObject.has("viewCount")) {
					    //it has it, do appropriate processing
						videoInfo[counter]=jsonObject.getString("viewCount");						
					}else{
						videoInfo[counter]="0";
					}
					//videoInfo[counter]=jsonObject.getString("viewCount");
					counter++;
					videoInfo[counter]=jsonObject.getString("title");
					counter++;
					videoInfo[counter]=jsonObject.getString("description");
					counter++;

					Log.v("check videoInfo, uploaded",videoInfo[1]);
					Log.v("check videoInfo, viewCount",videoInfo[2]);
					Log.v("check videoInfo, title",videoInfo[3]);
					Log.v("check videoInfo, description",videoInfo[4]);
					
					JSONObject thumbnailObject = jsonObject.getJSONObject("thumbnail");
					videoInfo[counter]=thumbnailObject.getString("sqDefault");
					counter++;
					/*					
					 */
					JSONObject playerObject = jsonObject.getJSONObject("player");
					if(playerObject.has("default")) {
					    //it has it, do appropriate processing
						videoInfo[counter]=playerObject.getString("default");
						
					}else{
						videoInfo[counter]="nil";
					}
					counter++;
					Log.v("check videoInfo, thumbnail", thumbnailObject.getString("sqDefault"));
					JSONObject contentObject = jsonObject.getJSONObject("content");
					if(contentObject.has("5")) {
					    //it has it, do appropriate processing
						videoInfo[counter]=contentObject.getString("5");
						
					}else{
						videoInfo[counter]="nil";
					}
					counter++;
					if(contentObject.has("1")) {
					    //it has it, do appropriate processing
						videoInfo[counter]=contentObject.getString("1");
						
					}else{
						videoInfo[counter]="nil";
					}
					counter++;
					
					videoInfo[counter]=jsonObject.getString("duration");
					counter++;		
					Log.v("check videoInfo, rtsp", contentObject.getString("1"));
					Log.v("check videoInfo, duration", jsonObject.getString("duration"));
					arrayCounter++;
					}
				} 
			catch (JSONException e) {
				e.printStackTrace();
				return null;
				}
			Log.v("Check point! in if", "arrayCounter=" +arrayCounter+".");
    		// TODO index changed
    		return videoInfo;
		}
		else{return null;}
	}
	
	
	public String[] MyJSONToString(String Json){
		arrayCounter = 0;
		if(Json!=null){
			String[] videoInfo = new String[100];
			JSONArray jsonArray;
			try {
				jsonArray = new JSONArray(Json);
				//JSONObject dataObject = jsonRaw.getJSONObject("data"); // this is the "data": { } part
				//jsonArray = dataObject.getJSONArray("items");
				int counter=0;
				for (int i = 0; i < (jsonArray.length()); i++) {	
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					videoInfo[counter]=jsonObject.getString("video_id");
					counter++;
					videoInfo[counter]=jsonObject.getString("date");
					counter++;
					videoInfo[counter]=jsonObject.getString("category");
					counter++;
					videoInfo[counter]=jsonObject.getString("title");
					counter++;				
    				videoInfo[counter]=jsonObject.getString("thumbnail");
					counter++;								
					videoInfo[counter]=jsonObject.getString("duration");
					counter++;		
					videoInfo[counter]=jsonObject.getString("shared_link");
					counter++;	 
					videoInfo[counter]=jsonObject.getString("content");
					counter++;
					videoInfo[counter]=jsonObject.getString("view_count");
					counter++;								
					Log.v("check videoInfo, video_id",videoInfo[0+i*9]);
					Log.v("check videoInfo, date",videoInfo[1+i*9]);
					Log.v("check videoInfo, category",videoInfo[2+i*9]);	
					Log.v("check videoInfo, thumbnail",videoInfo[3+i*9]);
					Log.v("check videoInfo, duration",videoInfo[4+i*9]);
					Log.v("check videoInfo, shared_link",videoInfo[5+i*9]);	
					Log.v("check videoInfo, content",videoInfo[6+i*9]);
					Log.v("check videoInfo, view_count",videoInfo[7+i*9]);
		
					arrayCounter++;
					}
				} 
			catch (JSONException e) {
				e.printStackTrace();
				}
			Log.v("Check point! in if", "arrayCounter=" +arrayCounter+".");
    		// TODO index changed
    		return videoInfo;
		}
		else{return null;}
	}
	 
	
	public int GetCounter(){
		return arrayCounter*9;
	}
	
	
}
